package com.hz.house.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序获取token
 * @author hsk
 */
@Log4j2
@Service
public class WxMiniService {

    @Resource
    private RestTemplate ribbonTemplate;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 获取小程序token的服务地址 本系统
     */
    String GET_MINI_TOKEN_SERVICE = "http://house-small-building/ms/building/getXiaoChengxuTk";

    /**
     * 获取买房好帮手公众号token的服务地址 本系统
     */
    String GET_Gzh_TOKEN_SERVICE = "http://house-small-building/ms/building/getMaiFGzhTk";

    /**
     * 检查内容是否敏感的接口
     */
    private static final String CHECK_CONTENT_HOST= "https://api.weixin.qq.com/wxa/msg_sec_check";


    /**
     * 获取微信小程序token
     *
     * @return
     */
    public String getXiaoChengxuToken(String serviceUrl) {
        //买房好帮手 微信公众号
        String res = ribbonTemplate.getForObject(serviceUrl, String.class);
        JSONObject jo = JSON.parseObject(res);
        return jo.getString("data");
    }

    /**
     * 检查文字内容是否有敏感内容:使用腾讯
     * @param content
     * @return
     */
    public Boolean checkContent(String content) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("content", content);
        JSONObject json = new JSONObject(map);
        String res = doPostSendMsg(json.toJSONString(), addMiniAccessToken(CHECK_CONTENT_HOST));
        log.info("腾讯云校验结果:"+res);
        JSONObject result = JSON.parseObject(res);
        return result.getIntValue("errcode") == 0;
    }

    /**封装http请求发送post,返回接口的结果 */
    private String doPostSendMsg(String jsonData,String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
        return restTemplate.postForObject(url, entity, String.class);
    }


    public String addMiniAccessToken(String url) {
        String accessToken = getXiaoChengxuToken(GET_MINI_TOKEN_SERVICE);
        log.info( "获取到买房好帮手小程序Token:{}", accessToken);
        return add(url, accessToken);
    }

    public String addWxAccessToken(String url) {
        String accessToken = getXiaoChengxuToken(GET_Gzh_TOKEN_SERVICE);
        log.info( "获取到买房好帮手公众号Token:{}", accessToken);
        return add(url, accessToken);
    }

    private String add(String url, String accessToken){
        return url + (url.contains("?") ? "&" : "?") + "access_token=" + accessToken;
    }

}
